// XiaosangController.java
package com.hkbigdata.cryd.java.ai.langchain4j.controller;

import com.hkbigdata.cryd.java.ai.langchain4j.Bean.ChatForm;
import com.hkbigdata.cryd.java.ai.langchain4j.assistant.XiaosangAgent;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.Collections;
import java.util.Map;

@Tag(name = "小桑")
@RestController
@RequestMapping("/xiaosang")
public class XiaosangController {

    @Autowired
    private XiaosangAgent xiaosangAgent;

    // 流式对话接口
    @Operation(summary = "流式对话")
    @PostMapping(value = "/chat", produces = MediaType.APPLICATION_NDJSON_VALUE)
    public Flux<Map<String, String>> streamChat(@RequestBody ChatForm chatForm) {
        return xiaosangAgent.chat(chatForm.getMemoryId(), chatForm.getMessage())
                .map(message -> Collections.singletonMap("content", message))
                .onErrorResume(e -> Flux.just(
                        Collections.singletonMap("error", "服务异常: " + e.getMessage())
                ));
    }

    // 统一异常处理
    @ExceptionHandler(Exception.class)
    public Flux<Map<String, String>> handleException(Exception ex) {
        return Flux.just(Collections.singletonMap("error",
                "处理请求时发生错误: " + ex.getMessage()));
    }
}

